﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Infragistics.Win.UltraWinListView;
using log4net;

namespace WFFImporter
{
    public partial class Form1 : Form
    {
        private bool bAutoMode = false;
        public Form1()
        {
            InitializeComponent();
            Init();
        }
        public Form1(string[] args)
        {
            InitializeComponent();
            Init();
            if ("auto" == args[0].ToString().ToLower())
            {
                timer1.Enabled = true;
            }
        }
        private void Init()
        {
            lvComputerList.MainColumn.Text = "Computer Name";
            lvComputerList.SubItemColumns.Add("Site");
            lvComputerList.SubItemColumns.Add("Organization");
            lvComputerList.SubItemColumns.Add("Current User");
            lvComputerList.SubItemColumns.Add("OS");
            lvComputerList.SubItemColumns.Add("--Result--");
        }
        delegate void ShowTextDelegateStr(string sMsg);
        public void ShowText(string sMsg)
        {
            if (!rtbMsg.InvokeRequired)
            {
                while (rtbMsg.Lines.Length > 1000)
                {
                    string[] sLines = rtbMsg.Lines;
                    string[] sNewLines = new string[sLines.Length - 10];

                    Array.Copy(sLines, 10, sNewLines, 0, sNewLines.Length);
                    rtbMsg.Lines = sNewLines;
                }

                rtbMsg.AppendText(sMsg);
                rtbMsg.AppendText("\n");
            }
            else
            {
                ShowTextDelegateStr gShowText = new ShowTextDelegateStr(ShowText);
                this.BeginInvoke(gShowText, new object[] { sMsg });
            }
        }

        private void bOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog odlg = new OpenFileDialog();
            odlg.Title = "Select csv(tsv) file to Import";
            odlg.InitialDirectory = @"c:\";
            odlg.Filter = "csv File(*.csv)|*.csv|Txt File(*.txt)|*.txt";
            odlg.FilterIndex = 0;
            odlg.RestoreDirectory = true;
            string sFileName = "";
            if (odlg.ShowDialog() == DialogResult.OK)
            {
                sFileName = odlg.FileName;
            }
            else
            {
                return;
            }
            odlg.Dispose();

            FileStream file = new FileStream(sFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            StreamReader streamReader = new StreamReader(file);//设定读写的编码
            //使用StreamReader类来读取文件  
            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);


            string strLine = "";
            string[] record = new string[6];

            if (cbIncludeTitle.Checked)
            {
                strLine = streamReader.ReadLine();
                //strLine = streamReader.ReadLine();
            }

            strLine = streamReader.ReadLine();
            lvComputerList.Items.Clear();
            try
            {

                while (strLine != null)
                {
                    record = strLine.Split('\t');

                    UltraListViewSubItem[] subItemArray = new UltraListViewSubItem[5];
                    for (int i = 1; i <= 4; i++)
                    {
                        subItemArray[i - 1] = new UltraListViewSubItem();
                        subItemArray[i - 1].Value = record[i];
                    }
                    subItemArray[4] = new UltraListViewSubItem();
                    subItemArray[4].Value = "";
                    Infragistics.Win.UltraWinListView.UltraListViewItem item = new Infragistics.Win.UltraWinListView.UltraListViewItem(record[0], subItemArray);
                    lvComputerList.Items.Add(item);

                    strLine = streamReader.ReadLine();
                }
                streamReader.Close();
                file.Close();
                ultraStatusBar1.Panels[0].Text = lvComputerList.Items.Count.ToString() + " items loaded into system.";
            }
            catch (Exception ex)
            {

                streamReader.Close();
                file.Close();
                MessageBox.Show(ex.Message);
            }
        }

        private void bImport_Click(object sender, EventArgs e)
        {
            WriteIntoWFF();
        }

        private void bOpenAsset_Click(object sender, EventArgs e)
        {
            ReadFromDB();
        }

        private void ReadFromDB()
        {
            dsAssetList ds = new dsAssetList();
            dsAssetListTableAdapters.DataTable1TableAdapter adp = new dsAssetListTableAdapters.DataTable1TableAdapter();
            adp.Fill(ds.DataTable1);
            lvComputerList.Items.Clear();

            foreach (DataRow dr in ds.DataTable1.Rows)
            {
                UltraListViewSubItem[] subItemArray = new UltraListViewSubItem[5];

                subItemArray[0] = new UltraListViewSubItem();
                subItemArray[0].Value = dr["SiteIDName"].ToString();

                subItemArray[1] = new UltraListViewSubItem();
                subItemArray[1].Value = dr["OrgIDName"].ToString();

                subItemArray[2] = new UltraListViewSubItem();
                subItemArray[2].Value = dr["Username"].ToString();

                subItemArray[3] = new UltraListViewSubItem();
                subItemArray[3].Value = dr["OS"].ToString();

                subItemArray[4] = new UltraListViewSubItem();
                subItemArray[4].Value = "";

                Infragistics.Win.UltraWinListView.UltraListViewItem item = new Infragistics.Win.UltraWinListView.UltraListViewItem(dr["AssetID"].ToString(), subItemArray);
                lvComputerList.Items.Add(item);
            }
            string sMsg = lvComputerList.Items.Count.ToString() + " items loaded into system.";
            ultraStatusBar1.Panels[0].Text = sMsg;
            log4net.Logger.Debug(sMsg);
            ShowText(sMsg);
            
        }
        private void WriteIntoWFF()
        {
            string sComputerName = "";
            string sSite = "";
            string sOrg = "";
            string sCurrentUser = "";
            string sOS = "";
            string sDebugMsg = "";
            int iStatTotal = lvComputerList.Items.Count;
            int iStatInserted = 0;
            int iStatUpdated = 0;
            int iStatSkipped = 0;
            int iStatError = 0;
            //string strSQL=" ";
            SqlCommand cmd = new SqlCommand();
            SqlConnection connection = new SqlConnection(Properties.Settings.Default.WFFConnectionString);
            cmd.Connection = connection;

            ultraStatusBar1.Panels[1].ProgressBarInfo.Maximum = lvComputerList.Items.Count;
            ultraStatusBar1.Panels[1].ProgressBarInfo.Value = 0;
            foreach (Infragistics.Win.UltraWinListView.UltraListViewItem item in lvComputerList.Items)
            {
                sComputerName = item.Value.ToString().Trim();
                sSite = item.SubItems[0].Value.ToString();
                sOrg = item.SubItems[1].Value.ToString();
                sCurrentUser = item.SubItems[2].Value.ToString();
                sOS = item.SubItems[3].Value.ToString();

                dsComputerList ds = new dsComputerList();
                dsComputerListTableAdapters.Endpoint_Protection_StandingDataComputerListTableAdapter adp = new dsComputerListTableAdapters.Endpoint_Protection_StandingDataComputerListTableAdapter();
                adp.Fill(ds.Endpoint_Protection_StandingDataComputerList, sComputerName);
                int iCount = ds.Endpoint_Protection_StandingDataComputerList.Rows.Count;
                if (iCount == 0) //New Computer List
                {
                    dsStandingData ds1 = new dsStandingData();
                    dsStandingDataTableAdapters.Endpoint_Protection_StandingDataTableAdapter adp1 = new dsStandingDataTableAdapters.Endpoint_Protection_StandingDataTableAdapter();
                    adp1.Fill(ds1.Endpoint_Protection_StandingData);
                    if (ds1.Endpoint_Protection_StandingData.Rows.Count > 0)
                    {
                        Guid gParent = Guid.Parse(ds1.Endpoint_Protection_StandingData.Rows[0]["ID"].ToString());
                        string sParent = Convert.ToBase64String(gParent.ToByteArray());
                        Guid gIDComputer = Guid.NewGuid();
                        string sIDComputer = Convert.ToBase64String(gIDComputer.ToByteArray());
                        string sPath = "StandingData," + sParent + ",ComputerList," + sIDComputer + ",";

                        cmd.CommandText = "INSERT INTO [Endpoint_Protection_StandingDataComputerList] ";
                        cmd.CommandText += "([ComputerName]";
                        cmd.CommandText += ",[Site]";
                        cmd.CommandText += ",[Organization]";
                        cmd.CommandText += ",[CurrentUser]";
                        cmd.CommandText += ",[OS]";
                        cmd.CommandText += ",[_CreatedDate]";
                        cmd.CommandText += ",[_CreatedBy]";
                        cmd.CommandText += ",[ID]";
                        cmd.CommandText += ",[Parent_StandingData_ComputerList]";
                        cmd.CommandText += ",[_Path])";
                        cmd.CommandText += " VALUES ";
                        cmd.CommandText += " (@ComputerName ";
                        cmd.CommandText += ",@Site ";
                        cmd.CommandText += ",@Organization ";
                        cmd.CommandText += ",@CurrentUser ";
                        cmd.CommandText += ",@OS ";
                        cmd.CommandText += ",getdate() ";
                        cmd.CommandText += ",'eppadmin' ";
                        cmd.CommandText += ",@ID";
                        cmd.CommandText += ",@Parent_StandingData_ComputerList";
                        cmd.CommandText += ",@_Path )";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@ComputerName", SqlDbType.NVarChar, 255).Value = sComputerName;
                        cmd.Parameters.Add("@Site", SqlDbType.NVarChar, 255).Value = sSite;
                        cmd.Parameters.Add("@Organization", SqlDbType.NVarChar, 255).Value = sOrg;
                        cmd.Parameters.Add("@CurrentUser", SqlDbType.NVarChar, 255).Value = sCurrentUser;
                        cmd.Parameters.Add("@OS", SqlDbType.NVarChar, 255).Value = sOS;
                        cmd.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value = gIDComputer;
                        cmd.Parameters.Add("@Parent_StandingData_ComputerList", SqlDbType.UniqueIdentifier).Value = gParent;
                        cmd.Parameters.Add("@_Path", SqlDbType.NVarChar, 1000).Value = sPath;
                        if (cmd.Connection.State == ConnectionState.Closed)
                            cmd.Connection.Open();

                        int iResult = cmd.ExecuteNonQuery();
                        if (iResult == 0)
                        {
                            iStatError++;
                            sDebugMsg = "Sorry, Computer List Insert Error.";
                            //if (!bAutoMode)
                            //{
                            //    MessageBox.Show(sDebugMsg);
                            //}
                            ShowText(sDebugMsg);
                            Logger.Error(sDebugMsg);
                        }
                        else
                        {
                            iStatInserted++;
                            sDebugMsg = sComputerName + " imported to database successfully";
                            ShowText(sDebugMsg);
                            Logger.Error(sDebugMsg);
                        }
                    }



                }
                else if (iCount == 1) // Exist
                {
                    if ((sSite != ds.Endpoint_Protection_StandingDataComputerList.Rows[0]["Site"].ToString().Trim()) ||
                            (sOrg != ds.Endpoint_Protection_StandingDataComputerList.Rows[0]["Organization"].ToString().Trim()) ||
                            (sCurrentUser != ds.Endpoint_Protection_StandingDataComputerList.Rows[0]["CurrentUser"].ToString().Trim()) ||
                            (sOS != ds.Endpoint_Protection_StandingDataComputerList.Rows[0]["OS"].ToString().Trim())
                       )
                    {
                        cmd.CommandText = "update Endpoint_Protection_StandingDataComputerList set Site = @Site, Organization = @Organization , ";
                        cmd.CommandText += " CurrentUser = @CurrentUser, OS = @OS where ComputerName = @ComputerName ";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@Site", SqlDbType.NVarChar, 255).Value = sSite;
                        cmd.Parameters.Add("@Organization", SqlDbType.NVarChar, 255).Value = sOrg;
                        cmd.Parameters.Add("@CurrentUser", SqlDbType.NVarChar, 255).Value = sCurrentUser;
                        cmd.Parameters.Add("@OS", SqlDbType.NVarChar, 255).Value = sOS;
                        cmd.Parameters.Add("@ComputerName", SqlDbType.NVarChar, 255).Value = sComputerName;
                        if (cmd.Connection.State == ConnectionState.Closed)
                            cmd.Connection.Open();
                        int iResult = cmd.ExecuteNonQuery();
                        if (iResult == 0)
                        {
                            iStatError++;
                            sDebugMsg = "Sorry, Computer List Update Error.";
                            //if (!bAutoMode)
                            //{
                            //    MessageBox.Show(sDebugMsg);
                            //}
                            ShowText(sDebugMsg);
                            Logger.Error(sDebugMsg);
                        }
                        else
                        {
                            //MessageBox.Show("modified for" + sComputerName);
                            iStatUpdated++;
                            sDebugMsg = sComputerName + " updated to database successfully";
                            ShowText(sDebugMsg);
                            Logger.Debug(sDebugMsg);
                        }

                    }
                    else
                    {
                        iStatSkipped++;
                        sDebugMsg = sComputerName + " checked same with db, skipped";
                        ShowText(sDebugMsg);
                        Logger.Debug(sDebugMsg);
                        // MessageBox.Show("Skip for " + sComputerName);
                    }

                }
                else if (iCount > 1) // Duplicated
                {
                    // notify user for duplication
                    iStatSkipped++;
                    sDebugMsg = sComputerName + " duplicated in computer list db, skipped";
                    ShowText(sDebugMsg);
                    Logger.Error(sDebugMsg);

                }

                ultraStatusBar1.Panels[1].ProgressBarInfo.Value++;
                Application.DoEvents();
            }
            sDebugMsg = String.Format("Totally {0} records", iStatTotal) + '\n';
            sDebugMsg += String.Format("New Added:  {0} records", iStatInserted) + '\n';
            sDebugMsg += String.Format("Refresh:    {0} records", iStatUpdated) + '\n';
            sDebugMsg += String.Format("Skipped:    {0} records", iStatSkipped) + '\n';
            sDebugMsg += String.Format("Error:      {0} records", iStatError) + '\n';
            ShowText(sDebugMsg);
            Logger.Error(sDebugMsg);
        }
        private void bAutoSync_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;   
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            this.Text = "WFF Data Importer(Auto Running)";
            ReadFromDB();
            bAutoMode = true;
            WriteIntoWFF();
            Close();

        }
    }
}
